package com.controller.cook;

import java.io.File;

import javax.annotation.Resource;
import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.po.CookZ;
import com.po.ImageObject;
import com.service.cook.CookServiceZ;
@Controller
public class CookControllerZ {
	@Resource(name="cookServiceImpZ")
	private CookServiceZ coservice;
	@ResponseBody
	@RequestMapping(value="/findCookZ")
	public CookZ findCook(@RequestBody CookZ co,HttpServletRequest request){
		CookZ cook = coservice.findCook(co);
	
		return cook;
	}
	@ResponseBody
	@RequestMapping(value="/updateCookZ")
	public int updateCook(@RequestBody CookZ co){	
		return coservice.updateCook(co);
	}
	@ResponseBody
	@RequestMapping(value = "/updateImageZ")
	public int simages(@RequestBody ImageObject image,String state,String id,HttpServletRequest request) {
		byte[] imagebyte=image.getImage();
		if(state.equals("0")){
			CookZ cook = new CookZ();
			cook.setCookid(id);
			cook.setCoimpath(image.getImagename());
			coservice.updateCook(cook);
		}
		System.out.println("**************"+request.getServletContext().getRealPath("/images/cook/")+image.getImagename());
		int i=byte2image(imagebyte,request.getServletContext().getRealPath("/images/cook/")+image.getImagename());
		return i;
	}
	/**
	 * 将二进制转化为图片
	 * @param data
	 * @param path
	 * @return
	 */
	public  int byte2image(byte[] data, String path) {
		if (data.length < 3 || path.equals(""))
			return 0;
		try {
			FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
			imageOutput.write(data, 0, data.length);
			imageOutput.close();
			System.out.println("Make Picture success,Please find image in " + path);
			return 1;
			
		} catch (Exception ex) {
			System.out.println("Exception: " + ex);
			ex.printStackTrace();
			return 0;
		}
	}
}
